import React, { Component } from 'react'
import store from '../../redux/store'
import {createAddPersonAction} from '../../redux/actions/person'

export default class Person extends Component {
	state = {
		name:'',
		age:0
	}
	render() {
		const {he,rens} = store.getState()
		return (
			<div>
				<h3>我是Person组件</h3>
				<h4>上方的Count组件中的和是：{he}</h4>
				<input type="text" onChange={this.saveUserData('name')} placeholder="请输入名字"/><br/>
				<input type="text"  onChange={this.saveUserData('age')} placeholder="请输入年龄"/><br/>
				<button onClick={this.addPerson}>添加</button>
				<ul>
					{
						rens.map((personObj)=>{
							return <li key={personObj.id}>{personObj.name}-{personObj.age}</li>
						})
					}
					
				</ul>
			</div>
		)
	}
	saveUserData = (key)=>{
		return (event)=>{
			this.setState({[key]:event.target.value})
		}
	}
	addPerson = ()=>{
		const {name,age} = this.state
		const p = {id:Date.now(),name,age}
		store.dispatch(createAddPersonAction(p))
	}
	componentDidMount(){
		store.subscribe(()=>{
			this.forceUpdate()
		})
	}
}
